package com.ruoyi.hatha.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.huifu.adapay.Adapay;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.AdapayCommon;
import com.huifu.adapay.model.MerConfig;
import com.huifu.adapay.model.SettleAccount;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.hatha.domain.PBankCard;
import com.ruoyi.hatha.service.IPBankCardService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * bankcardController
 * 
 * @author hatha
 * @date 2024-03-08
 */
@RestController
@RequestMapping("/hatha/bankcard")
public class PBankCardController extends BaseController
{
    @Autowired
    private IPBankCardService pBankCardService;

    /**
     * 查询bankcard列表
     */
    @PreAuthorize("@ss.hasPermi('hatha:bankcard:list')")
    @GetMapping("/list")
    public TableDataInfo list(PBankCard pBankCard)
    {
        startPage();
        List<PBankCard> list = pBankCardService.selectPBankCardList(pBankCard);
        return getDataTable(list);
    }

    /**
     * 导出bankcard列表
     */
    @PreAuthorize("@ss.hasPermi('hatha:bankcard:export')")
    @Log(title = "bankcard", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PBankCard pBankCard)
    {
        List<PBankCard> list = pBankCardService.selectPBankCardList(pBankCard);
        ExcelUtil<PBankCard> util = new ExcelUtil<PBankCard>(PBankCard.class);
        util.exportExcel(response, list, "bankcard数据");
    }

    /**
     * 获取bankcard详细信息
     */
    @PreAuthorize("@ss.hasPermi('hatha:bankcard:query')")
    @GetMapping(value = "/{cardId}")
    public AjaxResult getInfo(@PathVariable("cardId") String cardId)
    {
        return success(pBankCardService.selectPBankCardByCardId(cardId));
    }

    @GetMapping(value = "/getyue")
    public AjaxResult getyue() throws Exception {
        Long uid = SecurityUtils.getUserId();
        PBankCard pc = new PBankCard();
        pc.setUid(uid);
        List<PBankCard> lpc = pBankCardService.selectPBankCardList(pc);

        if(lpc.size()==0){
            return success(null);
        }

        PBankCard npc = lpc.get(0);


        Adapay.debug = true;
        Adapay.prodMode = true;
        String apiKey = "api_live_dc9dd8df-b9a9-4d58-a7ba-974bf75ac8cb";
        String mockApiKey = "api_test_d1f93046-b897-42cc-b726-1f6220260a60";
        String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJFwVx0ZBLTG7JdsXAsJ5XCZ59seRGyEdz3LCOIjuf+V4CVVQgzNruMGkYD6dWd1PIo/XJZLrzyaKd9DqR+SvJjMvl1QVsm2KdAQkzmfDIEYlk+aKf2rhJwgwHCjCZw76ORjQoywjHYJXAv/+gkA/TsoJOhnkk6VeF6k/zrRooSbAgMBAAECgYAB4TDPCHa+G2ANaPIblmontWWAuHhr6p5b5xbbTVjnC7nU4bAz2CiteHVC9Hm195brtnvs2VePcfKelxJFfTEAx2m/I1G4cU1OUgaOKRwUL1IrTbTPdyuMosXG4X4FHsxnBF7sANOzt3Budgu/1Wc00dI6DsA/WrWPs/kFUNHFUQJBAPYrKpWQgqeF95OUKfJtdogscsj+gbkl/z+dgskD5t7SlCGE4C5LF7BcDkUAx8Uq4s8yaeYzFaUI53BuBSUr/9MCQQCXP09sO+wTP+rTLFdoPe6jC60ZrH12v2OofgJSpbZTQeRsrYq7xUjYgHmBe9w9BMCc8BzjNOBlIHSgP9Gt8rMZAkEA3q9b3WKVnp/Ev37Xl1NIV5UF3SbGCMwDo/ODvP3HmqgZklzWQ2pwqnwL+IXlMUpDVLXBMJnjqaBtZLpR8zdjOwJAa7n9QPMhP8i74jNoAmhyS5FqdqnkJytEuWMfFmzPg1egckPdV8a6DvLbGH33LULwShfAC5jC52SJjQZHu6TtKQJABlE+ui8xYjNygH2Z/c+pstyerFT1DRZnpGBt2kQ2BUqW3+G8UA0OBhKtko01j48KbkBpw6sdd2VmPcm8ArBCGg==";
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setApiMockKey(mockApiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        Adapay.initWithMerConfig(merConfig);

        String appId = "app_cc612f06-2165-4e66-b6f6-5bb21975f0b8";

        Map<String, Object> queryParams = new  HashMap<String, Object>(5);
        queryParams.put("settle_account_id", npc.getId());
        queryParams.put("member_id", uid);
        queryParams.put("app_id", appId);
        Map<String, Object> settleCount = SettleAccount.balance(queryParams);
        return success(settleCount);
    }


    @GetMapping(value = "/getzdmx")
    public AjaxResult getzdmx(Integer page) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Date currentDate = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -6);


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Long uid = SecurityUtils.getUserId();
        PBankCard pc = new PBankCard();
        pc.setUid(uid);
        List<PBankCard> lpc = pBankCardService.selectPBankCardList(pc);

        if(lpc.size()==0){
            return success(null);
        }

        PBankCard npc = lpc.get(0);


        Adapay.debug = true;
        Adapay.prodMode = true;
        String apiKey = "api_live_dc9dd8df-b9a9-4d58-a7ba-974bf75ac8cb";
        String mockApiKey = "api_test_d1f93046-b897-42cc-b726-1f6220260a60";
        String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJFwVx0ZBLTG7JdsXAsJ5XCZ59seRGyEdz3LCOIjuf+V4CVVQgzNruMGkYD6dWd1PIo/XJZLrzyaKd9DqR+SvJjMvl1QVsm2KdAQkzmfDIEYlk+aKf2rhJwgwHCjCZw76ORjQoywjHYJXAv/+gkA/TsoJOhnkk6VeF6k/zrRooSbAgMBAAECgYAB4TDPCHa+G2ANaPIblmontWWAuHhr6p5b5xbbTVjnC7nU4bAz2CiteHVC9Hm195brtnvs2VePcfKelxJFfTEAx2m/I1G4cU1OUgaOKRwUL1IrTbTPdyuMosXG4X4FHsxnBF7sANOzt3Budgu/1Wc00dI6DsA/WrWPs/kFUNHFUQJBAPYrKpWQgqeF95OUKfJtdogscsj+gbkl/z+dgskD5t7SlCGE4C5LF7BcDkUAx8Uq4s8yaeYzFaUI53BuBSUr/9MCQQCXP09sO+wTP+rTLFdoPe6jC60ZrH12v2OofgJSpbZTQeRsrYq7xUjYgHmBe9w9BMCc8BzjNOBlIHSgP9Gt8rMZAkEA3q9b3WKVnp/Ev37Xl1NIV5UF3SbGCMwDo/ODvP3HmqgZklzWQ2pwqnwL+IXlMUpDVLXBMJnjqaBtZLpR8zdjOwJAa7n9QPMhP8i74jNoAmhyS5FqdqnkJytEuWMfFmzPg1egckPdV8a6DvLbGH33LULwShfAC5jC52SJjQZHu6TtKQJABlE+ui8xYjNygH2Z/c+pstyerFT1DRZnpGBt2kQ2BUqW3+G8UA0OBhKtko01j48KbkBpw6sdd2VmPcm8ArBCGg==";
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setApiMockKey(mockApiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        Adapay.initWithMerConfig(merConfig);

        String appId = "app_cc612f06-2165-4e66-b6f6-5bb21975f0b8";

        Map<String, Object> acctFlowParams = new HashMap<>();
        acctFlowParams.put("adapay_func_code", "acct.flow.list");
        acctFlowParams.put("app_id", appId);
        acctFlowParams.put("member_id", npc.getUid().toString());
        acctFlowParams.put("acct_type", "01");
        acctFlowParams.put("page_index", page.toString());
        acctFlowParams.put("page_size", "100");
        acctFlowParams.put("begin_date", sdf.format(calendar.getTime()));
        acctFlowParams.put("end_date", sdf.format(new Date()).toString());
        System.out.println(acctFlowParams);
        Map<String, Object> acctFlowList = AdapayCommon.queryAdapay(acctFlowParams);
        return success(acctFlowList);
    }

    /**
     * 新增bankcard
     */
    @PreAuthorize("@ss.hasPermi('hatha:bankcard:add')")
    @Log(title = "bankcard", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PBankCard pBankCard)
    {
        return toAjax(pBankCardService.insertPBankCard(pBankCard));
    }

    /**
     * 修改bankcard
     */
    @PreAuthorize("@ss.hasPermi('hatha:bankcard:edit')")
    @Log(title = "bankcard", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PBankCard pBankCard)
    {
        return toAjax(pBankCardService.updatePBankCard(pBankCard));
    }

    /**
     * 删除bankcard
     */
    @PreAuthorize("@ss.hasPermi('hatha:bankcard:remove')")
    @Log(title = "bankcard", businessType = BusinessType.DELETE)
	@DeleteMapping("/{cardIds}")
    public AjaxResult remove(@PathVariable String[] cardIds)
    {
        return toAjax(pBankCardService.deletePBankCardByCardIds(cardIds));
    }

    @GetMapping(value = "/getMyCard")
    public AjaxResult getMyCard()
    {
        Long userId = SecurityUtils.getUserId();

        PBankCard bc = new PBankCard();
        bc.setUid(userId);
        List<PBankCard> lbc = pBankCardService.selectPBankCardList(bc);

        if(lbc.isEmpty()){
            return AjaxResult.error(1,"未绑定结算卡");
        }else{
            return AjaxResult.success(lbc.get(0));
        }
    }
    @GetMapping(value = "/addCard")
    public AjaxResult addCard(PBankCard bc) throws Exception {
        Long userId = SecurityUtils.getUserId();
        bc.setUid(userId);


        Adapay.debug = true;
        Adapay.prodMode = true;
        String apiKey = "api_live_dc9dd8df-b9a9-4d58-a7ba-974bf75ac8cb";
        String mockApiKey = "api_test_d1f93046-b897-42cc-b726-1f6220260a60";
        String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJFwVx0ZBLTG7JdsXAsJ5XCZ59seRGyEdz3LCOIjuf+V4CVVQgzNruMGkYD6dWd1PIo/XJZLrzyaKd9DqR+SvJjMvl1QVsm2KdAQkzmfDIEYlk+aKf2rhJwgwHCjCZw76ORjQoywjHYJXAv/+gkA/TsoJOhnkk6VeF6k/zrRooSbAgMBAAECgYAB4TDPCHa+G2ANaPIblmontWWAuHhr6p5b5xbbTVjnC7nU4bAz2CiteHVC9Hm195brtnvs2VePcfKelxJFfTEAx2m/I1G4cU1OUgaOKRwUL1IrTbTPdyuMosXG4X4FHsxnBF7sANOzt3Budgu/1Wc00dI6DsA/WrWPs/kFUNHFUQJBAPYrKpWQgqeF95OUKfJtdogscsj+gbkl/z+dgskD5t7SlCGE4C5LF7BcDkUAx8Uq4s8yaeYzFaUI53BuBSUr/9MCQQCXP09sO+wTP+rTLFdoPe6jC60ZrH12v2OofgJSpbZTQeRsrYq7xUjYgHmBe9w9BMCc8BzjNOBlIHSgP9Gt8rMZAkEA3q9b3WKVnp/Ev37Xl1NIV5UF3SbGCMwDo/ODvP3HmqgZklzWQ2pwqnwL+IXlMUpDVLXBMJnjqaBtZLpR8zdjOwJAa7n9QPMhP8i74jNoAmhyS5FqdqnkJytEuWMfFmzPg1egckPdV8a6DvLbGH33LULwShfAC5jC52SJjQZHu6TtKQJABlE+ui8xYjNygH2Z/c+pstyerFT1DRZnpGBt2kQ2BUqW3+G8UA0OBhKtko01j48KbkBpw6sdd2VmPcm8ArBCGg==";
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setApiMockKey(mockApiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        Adapay.initWithMerConfig(merConfig);

        String appId = "app_cc612f06-2165-4e66-b6f6-5bb21975f0b8";

        Map<String, Object> settleCountParams = new  HashMap<String, Object>(4);
        Map<String, Object> accountInfo = new  HashMap<String, Object>(9);
        accountInfo.put("card_id",bc.getCardId());
        accountInfo.put("card_name",bc.getCardName());
        accountInfo.put("cert_id",bc.getCertId());
        accountInfo.put("cert_type","00");
        accountInfo.put("tel_no",bc.getTelNo());
        accountInfo.put("bank_acct_type","2");
        settleCountParams.put("member_id", userId);
        settleCountParams.put("app_id", appId);
        settleCountParams.put("channel","bank_account");
        settleCountParams.put("account_info", accountInfo);
        Map<String, Object> settleCount = SettleAccount.create(settleCountParams);
        //{"member_id":"115","create_time":"1709867330","prod_mode":"true","channel":"bank_account","account_info":{"bank_code":"01040000","cert_type":"00","tel_no":"1573333****","area_code":"3100","card_name":"董斌杰","bank_name":"","cert_id":"1305221993******12","bank_acct_type":"2","prov_code":"0031","card_id":"6217855000********6"},"id":"0583583570063680","app_id":"app_cc612f06-2165-4e66-b6f6-5bb21975f0b8","object":"settle_account","status":"succeeded"}
        String status = settleCount.get("status").toString();
        System.out.println(settleCount);
        if("succeeded".equals(status)){
            bc.setId(settleCount.get("id").toString());
            return toAjax(pBankCardService.insertPBankCard(bc));
        }else{
            return AjaxResult.error("错误",settleCount);
        }
    }

}
